package com.innjia.sys.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.innjia.base.utils.PageUtils;
import com.innjia.base.utils.Query;
import com.innjia.sys.entity.ContractInfoEntity;
import com.innjia.sys.service.CreditArchivesService;
import com.xiaoleilu.hutool.http.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 诚信档案-支付宝-区块链实现
 * <br>
 * 2017-11-29
 *
 * @author zhouxianglh@gmail.com
 */
@Service("creditArchivesServiceAlipay")
public class CreditArchivesServiceAlipayImpl implements CreditArchivesService {
    private static final Logger LOGGER = LoggerFactory.getLogger(CreditArchivesServiceAlipayImpl.class);

    @Value("${credit.alipay.blockLink.url}")
    private String blockLinkUrl;

    @Value("${aliPay.blockChain.schemaName.contract}")
    private String schemaName;

    public static void main(String[] args) {
        String json = "{\"bizNo\":\"系统请求流水号\",\"success\":true,\"resultMsg\":\"结果返回信息\",\"data\":{\"certNo\":\"XXX\",\"certType\":\"ID_CARD\",\"certName\":\"XXX\",\"role\":\"TENANT\",scene:\"rent\",recordsNum:\"3\",\"contents\":[{\"houseType\":\"PRIVATE\",\"records\":[{\"houseId\":\"123456\",\"leaseAddress\":\"XXX\",\"landlordName\":\"房东姓名\",\"tenantName\":\"租客姓名\",\"contractValidityStartTime\":\"2017-10-15 14:10:10\",\"contractValidityEndTime\":\"2017-11-15 14:10:10\",\"contractStatus\":\"PROCESSING\",\"monthRent\":\"2000\"}]},{\"houseType\":\"PRIVATE\",\"records\":[{\"houseId\":\"12345678\",\"leaseAddress\":\"SSS\",\"landlordName\":\"房东姓名\",\"tenantName\":\"租客姓名\",\"contractValidityStartTime\":\"2018-10-15 14:10:10\",\"contractValidityEndTime\":\"2019-11-15 14:10:10\",\"contractStatus\":\"NOT_BEGIN\",\"monthRent\":\"2200\"}]}],\"latestUpdateDate\":\"2017-11-15 14:10:15\"}}";
        PageUtils pageUtils = converValue(1, 1, json);
        System.out.println(pageUtils.toString());
    }

    private static PageUtils converValue(int pageSize, int pageNum, String jsonStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        Boolean isSuccess = jsonObject.getBoolean("success");
        if (null == isSuccess || !isSuccess) {
            throw new RuntimeException("调用接口出错:" + jsonStr);
        }
        List<ContractInfoEntity> list = new ArrayList<>();
        JSONObject data = jsonObject.getJSONObject("data");
        int total = data.getIntValue("recordsNum");
        PageUtils pageUtils = new PageUtils(list, total, pageSize, pageNum);
        JSONArray contents = data.getJSONArray("contents");
        contents.forEach(contentObj -> {
            JSONObject content = (JSONObject) contentObj;
            JSONArray records = content.getJSONArray("records");
            records.forEach(recordObj -> {
                JSONObject record = (JSONObject) recordObj;
                ContractInfoEntity bean = new ContractInfoEntity();
                bean.setHouseId(record.getString("houseId"));
                bean.setLeaseAddress(record.getString("leaseAddress"));
                bean.setMonthRent(record.getBigDecimal("monthRent"));
                bean.setTenantName(record.getString("tenantName"));
                bean.setLandlordName(record.getString("landlordName"));
                bean.setContractValidityStartTime(record.getDate("contractValidityStartTime"));
                bean.setContractValidityEndTime(record.getDate("contractValidityEndTime"));
                String status = record.getString("contractStatus");
                //这里合同 已签约,已作废 与区块链上不符,所以稍作处理
                if ("FINISH".equals(status)) {
                    bean.setContractStatus("2");
                } else {
                    bean.setContractStatus("1");
                }
                list.add(bean);
            });
        });
        return pageUtils;
    }

    @Override
    public PageUtils queryContract(Query query) {
        query.put("schemaName", schemaName);
        Params params = Params.getInstanse(query);
        String jsonStr = JSONObject.toJSONString(params);
        String result = HttpUtil.post(blockLinkUrl, jsonStr);
        LOGGER.error(result);
        return converValue(params.pageSize, params.getPageNum(), result);
    }

    /**
     * 请求参数
     */
    static class Params {
        public static final String ROLE_TENANT = "TENANT";

        public static final String ROLE_LANDLORD = "LANDLORD";

        public static final String CERT_TYPE_CERT_CART = "CERT_CARD";

        public static final String CERT_TYPE_PASSPORT = "PASSPORT";

        private String certType;

        private String certId;

        private String certName;

        private String role;

        private String schemaName;

        private int pageNum;

        private int pageSize;

        public static Params getInstanse(Query query) {
            Params bean = new Params();
            //现阶段只有租客
            bean.role = "TENANT";
            //租房合同现在只支持身份证
            bean.certType = CERT_TYPE_CERT_CART;
            bean.certId = (String) query.get("tenantIdCard");
            bean.certName = (String) query.get("tenantName");
            //TODO 这个暂时没还以,要补上
            bean.schemaName = (String) query.get("schemaName");
            bean.pageNum = query.getPage();
            bean.pageSize = query.getLimit();
            return bean;
        }

        public String getCertType() {
            return certType;
        }

        public String getCertId() {
            return certId;
        }

        public String getCertName() {
            return certName;
        }

        public String getRole() {
            return role;
        }

        public String getSchemaName() {
            return schemaName;
        }

        public int getPageNum() {
            return pageNum;
        }

        public int getPageSize() {
            return pageSize;
        }
    }
}
